<template xmlns="el">
  <div id="content">
    <globle-linear-border>
      <el-card class="searchBox">
        <el-form :inline="true">
          <el-form-item label="姓名">
            <el-input v-model="pageQuery.otherParams.name" placeholder="输入教师姓名搜索" clearable />
          </el-form-item>
          <el-form-item label="工号">
            <el-input v-model="pageQuery.otherParams.workId" placeholder="输入教师工号搜索" clearable />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="pageQuery.otherParams.sex" placeholder="选择教师性别搜索" clearable>
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="身份证">
            <el-input v-model="pageQuery.otherParams.identityId" placeholder="输入教师身份证搜索" clearable />
          </el-form-item>
          <el-form-item label="是否为管理员">
            <el-select v-model="pageQuery.otherParams.isAdmin" placeholder="选择是否为管理员搜索" clearable>
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="pageQuery.otherParams.isResigned" placeholder="选择状态搜索" clearable>
              <el-option label="在职" value="0" />
              <el-option label="辞职" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <section>
              <el-button type="primary" icon="Search" @click.stop="getPageInfo">搜 索</el-button>
              <el-button type="warning" icon="RefreshRight" @click.stop="reset">重 置</el-button>
              <el-button type="success" icon="Plus" @click="onAdd">添加教师</el-button>
              <el-button type="danger" icon="Minus" @click="onBatchDelete">批量辞退</el-button>
              <el-upload ref="uploadRef" :action="api.teacher.fileImportUrl" :show-file-list="false" 
                :on-progress="onProgress" :on-success="onSuccess" accept=".xlsx" :limit="1" :headers="headers">
                <el-button type="warning" icon="Download">导入数据</el-button>
              </el-upload>
              <el-button type="warning" icon="Upload" @click="onExpose">导出数据</el-button>
            </section>
          </el-form-item>
        </el-form>
      </el-card>
    </globle-linear-border>

    <globle-linear-border style="margin-top: 20px">
      <el-card class="mainBox">
        <span v-if="tableData.rows">
          <el-table :border="true" stripe ref="tableRef" :data="tableData.rows" @selection-change="onSelectChange"
            cell-class-name="table-cell" header-cell-class-name="table-header-cell">
            <el-table-column type="selection" width="55" />
            <el-table-column property="workId" label="工号" width="110" show-overflow-tooltip />
            <el-table-column property="name" label="姓名" width="120" />
            <el-table-column label="性别">
              <template #default="scope">{{ scope.row.sex === 1 ? '男' : '女' }}</template>
            </el-table-column>
            <el-table-column property="qq" label="QQ号" width="120" />
            <el-table-column property="phone" label="手机号" width="140" />
            <el-table-column property="identityId" label="身份证号" width="200" />
            <el-table-column label="是否为管理员">
              <template #default="scope">
                <el-tag effect="dark" type="success" v-if="scope.row.isAdmin == 1">是</el-tag>
                <el-tag effect="dark" type="danger" v-else>否</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态">
              <template #default="scope">
                <el-tag effect="dark" type="danger" v-if="scope.row.isResigned == 1">辞职</el-tag>
                <el-tag effect="dark" type="success" v-else>在职</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="300">
              <template #default="scope">
                <el-button type="primary" size="small" icon="Edit" :disabled="isMe(scope.row.workId)" @click="onEdit(scope.row)">修改</el-button>
                <el-button v-if="scope.row.isAdmin === 1" type="warning" size="small" icon="Setting" :disabled="isMe(scope.row.workId)" @click="onAdmin(scope.row)">取消管理员</el-button>
                <el-button v-else type="success" size="small" icon="Setting" @click="onAdmin(scope.row)">设为管理员</el-button>
                <el-button v-if="scope.row.isResigned === 0" type="danger" size="small" icon="Delete" :disabled="isMe(scope.row.workId)" @click="onDelete(scope.row)">辞退</el-button>
                <el-button v-else type="warning" size="small" icon="RefreshRight" @click="onDelete(scope.row)">恢复</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination v-model:currentPage="pageQuery.pageParams.pageNum"
            v-model:page-size="pageQuery.pageParams.pageSize" :page-sizes="pageSizeOption" :background="true"
            :small="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.totalSize"
            @size-change="onSizeChange" @current-change="onCurrentChange" />
        </span>
      </el-card>
    </globle-linear-border>
    <!-- 弹窗 -->
    <suspense>
      <dialog-vue ref="dialogRef" @onReGetData="getPageInfo"></dialog-vue>
    </suspense>
    <export-dialog ref="exportDialogRef"></export-dialog>
  </div>
</template>

<script lang="ts" setup>
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, ElNotification, ElTable, UploadFile } from 'element-plus';
import { IPageRes, ITch, APIData, ITchPageParams } from '../../../type';
import { useUserStore } from '../../../store/user';
import { useAPI } from '../../../request/api';
import ExportDialog from './ExportDialog.vue';
import { computed } from 'vue';
//注意!!定义动态引入组件时需要使用defineAsyncComponent，并且在template中需要搭配suspense组件使用,它是一个异步组件解决方案。
const DialogVue = defineAsyncComponent(() => import('./Dialog.vue'));
const store = useUserStore();

onMounted(() => {
  getPageInfo();
});

const api = useAPI();
const uploadRef = ref();
const dialogRef = ref();
const exportDialogRef = ref();
const tableRef = ref<InstanceType<typeof ElTable>>();
  let headers = {'token': localStorage.getItem('token')}
// const uploadUrl = api.teacher.fileImportUrl;

let deleteIdList = [] as Array<string>;
const pageSizeOption = [5, 10, 15, 20];
const pageQuery = reactive<ITchPageParams>({
  otherParams: {
    isResigned: '',
    isAdmin: '',
    name: '',
    sex: '',
    workId: '',
    identityId: ''
  },
  pageParams: {
    pageNum: 1,
    pageSize: pageSizeOption[1],
    sortField: '',
    sortType: '',
  },
});
const tableData = ref({} as IPageRes);

const isMe = computed(() => (rowWorkId: string) => rowWorkId == store.userInfo.workId);

const reset = () => {
  pageQuery.otherParams = {
    isResigned: '',
    isAdmin: '',
    name: '',
    sex: '',
    workId: '',
    identityId: ''
  }
  pageQuery.pageParams = {
    pageNum: 1,
    pageSize: pageSizeOption[1],
    sortField: '',
    sortType: ''
  }
  getPageInfo();
}

const onEdit = (row: ITch) => {
  dialogRef.value.openDialogByEdit(row);
};

const onAdmin = async (row: ITch) => {
  if (row.isAdmin === 1) {
    row.isAdmin = 0;
    postModify(row, '取消成功');
  } else {
    row.isAdmin = 1;
    postModify(row, '设置成功');
  }
};

const onDelete = (row: ITch) => {
  if (row.isResigned === 0) {
    ElMessageBox.confirm('您将辞退该教师,确定继续吗?', '提示', { type: 'warning' })
      .then(() => {
        deleteIdList.push(row.id);
        deleteInfo();
      })
      .catch(() => { });
  } else if (row.isResigned === 1) {
    row.isResigned = 0;
    postModify(row, '恢复成功');
  }
};
const onAdd = () => {
  dialogRef.value.openDialogByAdd();
};

const postModify = async (row: ITch, message: string) => {
  const res: APIData = await api.teacher.save(row);
  if (res.code === 200) ElMessage.success(message);
  else ElMessage.error(res.message);
};

//上传进行
const onProgress = (evt: any, uploadFile: UploadFile) => {
  ElMessage.success(`${uploadFile.name}正在上传中`);
};
//上传完成
const onSuccess = (response: APIData, uploadFile: UploadFile) => {
  if (response.code == 200) {
    getPageInfo();
    uploadRef.value.clearFiles();
    ElNotification.success(`${uploadFile.name}上传成功`);
  } else {
    ElNotification.error({title: `${response.message}`,message: `${response.data}`});
    uploadRef.value.clearFiles();
  }
};

//导出
const onExpose = async () => {
  exportDialogRef.value.open();
};

//分页大小
const onSizeChange = (val: number) => {
  pageQuery.pageParams.pageSize = val;
  pageQuery.pageParams.pageNum = 1;
  getPageInfo();
};
//分页页码
const onCurrentChange = (val: number) => {
  pageQuery.pageParams.pageNum = val;
  getPageInfo();
};

//勾选(仅收集删除数据)
const onSelectChange = (rowList: ITch[]) => {
  deleteIdList = [] as Array<string>;
  rowList.forEach(item => {
    deleteIdList.push(item.id);
  });
};
//勾选删除
const onBatchDelete = () => {
  if (deleteIdList.length !== 0)
    ElMessageBox.confirm('您将辞退勾选的教师,确定继续吗?', '提示', { type: 'warning' })
      .then(() => {
        deleteInfo();
      })
      .catch(() => { });
  else ElMessage.error('未勾选任何数据');
};

const getPageInfo = async () => {
  const res = await api.teacher.findPage(pageQuery);
  tableData.value = res.data;
};
const deleteInfo = async () => {
  const res = await api.teacher.delete(deleteIdList);
  if (res.data) {
    ElMessage({
      type: 'success',
      message: '辞退成功',
    });
    getPageInfo();
  }
};
</script>

<style lang="scss" scoped>
#content {
  height: 100%;
  padding: 14px 32px;

  .searchBox {
    &-item {
      margin-right: 10px;
    }

    // :deep(.el-form-item) {
    //   margin-bottom: 8px;
    // }

    :deep(.el-card__body) {
      display: flex;
      justify-content: space-between;
    }

    section {
      display: flex;
    }

    :deep(.el-input__wrapper) {
      width: 200px;
    }
  }

  .mainBox {
    :deep(.el-checkbox__inner) {
      background-color: var(--main-color);
      transition: background 0.3s ease;
    }

    :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: var(--active-color);
      transition: background 0.3s ease;
    }
  }
}
</style>
